<template>
  <div class="search-item" :class="{ active: visible, isSelect: !!filterLocalDateValue, 'date-item': formItem.props?.showDelete === false }" @click="visible = !visible">
    <span class="label">{{ formItem.props?.label }}<span v-if="filterLocalDateValue">:</span></span>
    <span class="text date-text">{{ filterLocalDateValue }}</span>
    <el-date-picker v-bind="{ ...attr }" v-model:modelValue="localDateValue" class="search-bar-date-picker" size="small" :value-format="attr['valueFormat'] || attr['value-format'] || 'YYYY-MM-DD'" @change="changeHandler" />
    <el-icon class="array-icon" :size="10" color="#999">
      <svg-icon name="ep:caret-bottom" />
    </el-icon>
    <el-icon class="delete-icon" :size="10" color="#999" @click.stop="clear">
      <svg-icon name="ep:circle-close-filled" />
    </el-icon>
  </div>
</template>

<script>
export default {
  inheritAttrs: false
}
</script>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { isEqual } from 'lodash-es'

const props = defineProps({
  fields: [Object, Array, String],
  formItem: Object,
  attr: {
    type: Object,
    default: () => {
      return { placeholder: '请选择', 'value-format': 'YYYY-MM-DD' }
    }
  }
})
const emit = defineEmits(['update:fields', 'search'])

const localDateValue = ref(null)
const visible = ref(false)

const changeHandler = e => {
  emit('update:fields', e)
  emit('search')
  visible.value = false
}

watch(() => props.fields, (newVal, oldVal) => {
  if (!isEqual(newVal, oldVal)) {
    localDateValue.value = newVal
  }
})

const filterLocalDateValue = computed(() => {
  if (localDateValue.value) {
    if (Array.isArray(localDateValue.value)) {
      return localDateValue.value.join(' - ')
    } else {
      return localDateValue.value
    }
  }
  return ''
})

function clear() {
  localDateValue.value = null
  emit('update:fields', null)
  emit('search')
}

onMounted(() => {
  localDateValue.value = props.fields
})

</script>

<style scope lang="scss">
@import "search";
</style>
